<?php
// +----------------------------------------------------------------------
// | 系统框架
// +----------------------------------------------------------------------
// | 版权所有 2017~2020 路人甲乙科技有限公司 [ http://www.lurenjiayi.com ]
// +----------------------------------------------------------------------
// | 官方网站：http://www.lurenjiayi.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\agents\admin;
use app\admin\controller\Agents;
use app\common\builder\ZBuilder;
use app\market\model\Position;
use app\user\model\Role as RoleModel;
use app\user\model\User as UserModel;
use think\Controller;
use app\money\model\Recharge as RechargeModel;
use app\money\model\Withdraw as WithdrawModel;
use app\money\model\Money as MoneyModel;
use think\Db;
use  think\helper\Hash;
class Indexmember extends controller{
	public function __construct()
    {
        parent::__construct();
		$mid = MID;
		
		$user = get_agents_info_admin($mid);
		$agent_pro = $user['agent_pro'];
		//$agent_rate = agents_back_rate($mid);
		
		if($user['agent_rate']){
			$rate = $user['agent_rate'];
		}else{
			//$rate =agents_back_rate($mid);
		}

		$plu_rate = $rate;

        $this->assign('agent_id',$user['agent_id']);
		//$this->assign('agent_rate',$agent_rate);
		$this->assign('agent_pro',$agent_pro);
		//$this->assign('plu_rate',$plu_rate);
        $this->assign('active', 'invite');
		
		// 设置分页参数
        $this->setPageParam();
    }

	 /**
     * 首页
     * @author 路人甲乙
     * @return mixed
     */
    public function index()
    {

		$mid = is_member_signin();
        if(!$mid){
            $this->error('请登陆后进行申请', URL('/login'));
        }
        $data=$res = Db::name('member_invitation_relation as r')
            ->join('member','member.id=r.invitation_mid','LEFT')
            ->field('r.id,r.mid,r.create_time,r.invitation_mid,member.name,member.mobile,member.agent_id,member.agent_far,member.agent_pro,member.id,member.agent_rate')
            ->where(['mid'=>$mid])
            ->paginate();
			
	
		$count_m= Db::name('member_invitation_relation')->where(['mid'=>$mid])->count();//邀请用户人数
  
        $count= Db::name('agents_back_money')->where(['mid'=>$mid])->sum('affect');//已赚取佣金
        $count = round($count,2);
        $rande=$this->rande($mid);
        $url=$this->http().$_SERVER['HTTP_HOST']."/register/id/".$rande.".html";//邀请链接
        $qrcode=$this->http().$_SERVER["SERVER_NAME"]."/member/invite/view";//二维码

        $this->assign('qrcode',$qrcode);
        $this->assign('url',$url);
		$this->assign('count_m',$count_m);
        $this->assign('count',$count);
        $this->assign('data',$data);
        $this->assign('share',config('share_title').config('share_content'));

        $this->assign('rate', config('rebate'));

		return $this->fetch(); // 渲染模板
	}
	public function award(){
		$mid = is_member_signin();
        if(!$mid){
            $this->error('请登陆后进行申请', URL('/login'));
        }

		 $count= Db::name('agents_back_money')->where(['mid'=>$mid])->sum('affect');//已赚取佣金
         $count = round($count,2);
        $data=$res = Db::name('agents_back_money')
            ->where(['mid'=>$mid])
            ->paginate();

		$count_m= Db::name('member_invitation_relation')->where(['mid'=>$mid])->count();//邀请用户人数
		$this->assign('count_m',$count_m);
        $rande=$this->rande($mid);
        $url=$this->http().$_SERVER["SERVER_NAME"]."/register/id/".$rande.".html";
        $this->assign('url',$url);
        $qrcode=$this->http().$_SERVER["SERVER_NAME"]."/member/invite/view";
        $this->assign('qrcode',$qrcode);
        $this->assign('count',$count);
        $this->assign('data',$data);
        $this->assign('rate', config('rebate'));
        $this->assign('share',config('share_title').config('share_content'));
        return $this->fetch();	
	}
	/*
     * 产生id混淆数
     */
    protected function rande($mid){
        return mt_rand(10,99).$mid.mt_rand(100,999);
    }
	//返回网址前缀
    protected function http(){
        return empty($_SERVER['HTTP_X_CLIENT_PROTO']) ? 'http://' : $_SERVER['HTTP_X_CLIENT_PROTO'] . '://';
    }
  
  
    /**
     * 新增
     * @author 路人甲乙
     * @return mixed
     */
    public function add()
    {
  
        if ($this->request->isPost()) {
              
            $data = $this->request->post();
            $data['mid'] = session('user_auth')['uid'];
          
            if($data['money']<0){
                $this->error('提现金额错误！');
            }
    
            $money_res=Db::name('money')->where(['mid'=>session('user_auth')['uid']])->find();
            if(empty($money_res['account'])){
                $this->error('查询账户资金出错！');
            }
            if(isset($money_res['account'])&&$money_res['account']/100<$data['money']){
                $this->error('提现金额已经大于可用余额！');
                exit;
            }
            $withdraw_info=Db::name('money_withdraw')
                ->where(['mid'=>session('user_auth')['uid']])
                ->where(['status'=>0])
                ->find();
            if(!empty($withdraw_info)){
                $this->error('您已有提现申请，请耐心等待审核。');
            }
            $c = Db::name('member')->where(["id"=>session('user_auth')['uid']])->find();
            if(Hash::check((string)$data['paywd'], $c['paywd'])){
                $res = WithdrawModel::saveData($data);
            }else{
                $this->error('支付密码错误');
            }
    		if($res['status']){
                $contentarr  = getconfigSms_status(['name'=>'stock_withdraw']);
                $content = str_replace(array("#var#","#amount#"),array($c['mobile'],$data['money']), $contentarr['value']);
                if($contentarr['status']==1){
                    sendsms_mandao('',$content,'');
                }
    			$this->success('提现申请已提交，请耐心等待审核', url('@member/index/index'));
    		}else{
    			$this->error('提现申请提交失败');
    		}
        }

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增') // 设置页面标题
            ->addFormItems([ // 批量添加表单项、
                ['text', 'money', '体现金额', '数字'],
                ['password', 'paywd', '支付密码', '支付密码'],
              
            ])
            ->fetch();         cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();

        // 数据列表
        $data_list = UserModel::where($map)->order('sort,id desc')->paginate();

        // 分页数据
        $page = $data_list->render();

        // 授权按钮
        $btn_access = [
            'title' => '授权',
            'icon'  => 'fa fa-fw fa-key',
            'href'  => url('access', ['uid' => '__id__'])
        ];

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('用户管理') // 设置页面标题
            ->setTableName('admin_user') // 设置数据表名
            ->setSearch(['id' => 'ID', 'username' => '用户名', 'email' => '邮箱']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['id', 'ID'],
                ['username', '用户名'],
                ['nickname', '昵称'],
                ['role', '角色', 'select', RoleModel::getTree(null, false)],
                ['email', '邮箱'],
                ['mobile', '手机号'],
                ['create_time', '创建时间', 'datetime'],
                ['status', '状态', 'switch'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add,enable,disable,delete') // 批量添加顶部按钮
            //->addRightButton('custom', $btn_access) // 添加授权按钮
            ->addRightButtons('edit,delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch(); // 渲染页面
    }
	
	public function detail(){
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		
        // 获取查询条件
		$map=[];
		$keyword = trim(input('param.keyword/s', ''));
		if($keyword<>""){
			$map['mobile'] = $keyword;
		}
		
		$filter_time      = input('param._filter_time/s', '');
		$filter_time_from = input('param._filter_time_from/s', '');
        $filter_time_to   = input('param._filter_time_to/s', '');
        if ($filter_time != '' && $filter_time_from != '' && $filter_time_to != '') {
            $map[$filter_time] = ['between time', [$filter_time_from.' 00:00:00', $filter_time_to.' 23:59:59']];
        }
		
		if(empty($map['detail_date'][1][0])){
            $beginday=date('Ymd',time()-2592000);//30天前
        }else{
            $beginday=date('Ymd',strtotime($map['detail_date'][1][0]));
        }
        if(empty($map['detail_date'][1][1])){
            $endday=date('Ymd',time());
        }else{
            $endday=date('Ymd',strtotime($map['detail_date'][1][1]));
        }
		unset($map['detail_date']);
		
		$GLOBALS['detail_costs'] = 0;
		$GLOBALS['detail_delays'] = 0;
		$GLOBALS['detail_buys'] = 0;
		$GLOBALS['detail_sells'] = 0;
		$GLOBALS['detail_earns'] = 0;
		$GLOBALS['detail_beginday'] = $beginday;
		$GLOBALS['detail_endday'] = $endday;
		
        // 数据列表		
        $data_list = Db::view('stock_borrow b')
            ->view("member", 'mobile,name,agent_far', 'member.id=b.member_id', 'left')
            ->view("stock_subaccount s",'sub_account','s.id=b.stock_subaccount_id','left')
            ->where($map)
			->where('agent_far',session('user_auth')['uid'])
            ->where('b.status=2')
			->where("b.end_time > " . strtotime($GLOBALS['detail_beginday']." 00:00:00"))
			->where("b.end_time < " . strtotime($GLOBALS['detail_endday']." 23:59:59"))
            ->order('b.create_time desc')
            ->paginate()
            ->each( function($item, $key){
                $item['deposit_money'] = money_convert($item['deposit_money']);
                $item['init_money'] = money_convert($item['init_money']);
                $item['borrow_money'] = money_convert($item['borrow_money']);
                $item['borrow_interest'] = money_convert($item['borrow_interest']);
                $item['stock_money'] = money_convert($item['stock_money']);
				$item['type'] = (int)$item['type'];
				if($item['type']===3){$unit='个月';}elseif($item['type']===2){$unit='周';}else{$unit='天';}
                $item['borrow_duration'] .= $unit;
				
				
                $item['cost'] = money_convert($item['deposit_money'] * $item['rate'] * $item['borrow_duration']  * 10);                
				$delay = ceil(($item['end_time'] - $item['verify_time']) / 86400) - $item['borrow_duration'];
				$item['delay'] = money_convert($item['deposit_money'] * $item['rate'] * $delay  * 10);				
				
				$item['cost'] = $item['borrow_interest'];   
				$item['delay'] = 0;
				$item['buy'] = Db::name('stock_delivery_order')->where(['sub_id'=>$item['stock_subaccount_id'],'business_name'=>'证券买入'])->sum('liquidation_amount-residual_quantity');
				$item['sell'] = Db::name('stock_delivery_order')->where(['sub_id'=>$item['stock_subaccount_id'],'business_name'=>'证券卖出'])->sum('residual_quantity-liquidation_amount');
                $item['earn'] = round($item['stock_money']-$item['init_money'],2);
				
				$GLOBALS['detail_costs'] = $GLOBALS['detail_costs'] + $item['cost'];
				$GLOBALS['detail_delays'] = $GLOBALS['detail_delays'] + $item['delay'];
				$GLOBALS['detail_buys'] = $GLOBALS['detail_buys'] + $item['buy'];
				$GLOBALS['detail_sells'] = $GLOBALS['detail_sells'] + $item['sell'];
				$GLOBALS['detail_earns'] = $GLOBALS['detail_earns'] + $item['earn'];
				
				return $item;
            });
		
        // 分页数据
        $page = $data_list->render();
		$html .= "<p style='padding-left:10px'>";
		$html .= "配置管理费："	.$GLOBALS['detail_costs']." 元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$html .= "延期费："		.$GLOBALS['detail_delays']." 元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$html .= "买入手续费："	.$GLOBALS['detail_buys']." 元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$html .= "卖出手续费："	.$GLOBALS['detail_sells']." 元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$html .= "盈亏："		.$GLOBALS['detail_earns']." 元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$html .= "</p>";

		
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')		
            ->setTableName('stock_borrow')
			->addTimeFilter('detail_date', [$beginday, $endday])
            ->setSearch(['mobile' => '商户手机号'],'','',true)
            ->addOrder('order_id,name,create_time') // 添加排序
            ->hideCheckbox()
            ->addColumns([ // 批量添加列
                ['order_id', '订单号'],
                ['mobile', '商户手机号'],
                ['cost','配资管理费（元）'],
				['delay', '延期费（元）'],
                ['buy','买入手续费（元）'],
                ['sell','卖出手续费（元）'],
                ['earn','盈亏（元）'],
				['verify_time','开始时间','datetime'],
				['end_time','终止时间','datetime'],
                //['right_button', '操作', 'btn']
            ])
			// 设置表格数据
            ->setRowList($data_list) 
			// 设置分页数据
			->setPages($page) 
			// 设置底部总计
			->setExtraHtml($html, 'table_bottom')
			// 渲染模板
            ->fetch(); 
   }
	
	public function gather(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
		
        // 获取查询条件
		$map=[];
		$keyword = trim(input('param.keyword/s', ''));
		if($keyword<>""){
			$map['mobile'] = $keyword;
		}
		
		$filter_time      = input('param._filter_time/s', '');
		$filter_time_from = input('param._filter_time_from/s', '');
        $filter_time_to   = input('param._filter_time_to/s', '');
        if ($filter_time != '' && $filter_time_from != '' && $filter_time_to != '') {
            $map[$filter_time] = ['between time', [$filter_time_from.' 00:00:00', $filter_time_to.' 23:59:59']];
        }
		
        //$map = $this->getMap();
		if(empty($map['gather_date'][1][0])){
            $beginday=date('Ymd',time()-2592000);//30天前
        }else{
            $beginday=date('Ymd',strtotime($map['gather_date'][1][0]));
        }
        if(empty($map['gather_date'][1][1])){
            $endday=date('Ymd',time());
        }else{
            $endday=date('Ymd',strtotime($map['gather_date'][1][1]));
        }
		unset($map['gather_date']);
		
		$GLOBALS['gather_recharges'] = 0;
		$GLOBALS['gather_withdraws'] = 0;
		$GLOBALS['gather_profits'] = 0;
		$GLOBALS['gather_beginday'] = $beginday;
		$GLOBALS['gather_endday'] = $endday;
		
        $data_list = Db::name('member')
            ->where($map)
            ->where('agent_far',session('user_auth')['uid'])
            ->paginate()
            ->each(function($item, $key){
				
				$count = Db::name('money_recharge')
							->where('mid',$item['id'])
							->where("create_time > " . strtotime($GLOBALS['gather_beginday']." 00:00:00"))
							->where("create_time < " . strtotime($GLOBALS['gather_endday']." 23:59:59"))
							->where('status=1')
							->sum('money');
				$item['count_recharge'] = money_convert($count);
				
				
				$count = Db::name('money_withdraw')
							->where('mid',$item['id'])
							->where("create_time > " . strtotime($GLOBALS['gather_beginday']." 00:00:00"))
							->where("create_time < " . strtotime($GLOBALS['gather_endday']." 23:59:59"))
							->where('status=1')
							->sum('money');
				$item['count_withdraw'] = money_convert($count);
				
				
				$count = Db::name('agents_back_money')
							->where('mid',$item['id'])
							->where("create_time > " . strtotime($GLOBALS['gather_beginday']." 00:00:00"))
							->where("create_time < " . strtotime($GLOBALS['gather_endday']." 23:59:59"))
							->sum('affect');
                $item['count_profit'] = round($count,2);
				
				
				
				$GLOBALS['gather_recharges'] = $GLOBALS['gather_recharges'] + $item['count_recharge'];
				$GLOBALS['gather_withdraws'] = $GLOBALS['gather_withdraws'] + $item['count_withdraw'];
				$GLOBALS['gather_profits'] = $GLOBALS['gather_profits'] + $item['count_profit'];
                return $item;
            });
		
        // 分页数据
        $page = $data_list->render();
		$html .= "<p style='padding-left:10px'>";
		$html .= "充值总金额："	.$GLOBALS['gather_recharges']." 元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$html .= "提现总金额："	.$GLOBALS['gather_withdraws']." 元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$html .= "佣金总金额："	.$GLOBALS['gather_profits']." 元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$html .= "</p>";
		
		
        return ZBuilder::make('table')
            ->setTableName('member')
			->addTimeFilter('gather_date', [$beginday, $endday])
            ->setSearch(['mobile' => '商户手机号'],'','',true)
            ->hideCheckbox()
            ->addColumns([
                ['id', 'ID'],
                ['mobile', '商户手机号'],
                ['name', '商户姓名'],
                ['count_recharge', '充值金额（元）'],
                ['count_withdraw', '提现金额（元）'],
                ['count_profit', '佣金金额（元）'],
            ])
			
			// 设置表格数据
            ->setRowList($data_list) 
			
			// 设置底部总计
			->setExtraHtml($html, 'table_bottom')
			
			// 渲染模板
            ->fetch(); 
   }
  
  
   public function getAgentDrowdro(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $map=array('member.agent_far'=>session('user_auth')['uid']);
        $data_list = RechargeModel::getAll($map, $order);
		
       // 分页数据
        $page = $data_list->render();
        if(empty($_SERVER["QUERY_STRING"])){
            $excel_url=substr(http().$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"],0,-
                5)."_export";
        }else{
            $excel_url=substr(http().$_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"],0,-
                5)."_export?".$_SERVER["QUERY_STRING"];
        }
        $btn_excel = [
            'title' => '导出EXCEL表',
            'icon'  => 'fa fa-fw fa-download',
            'href'  => url($excel_url,'','')
        ];
    	return ZBuilder::make('table')
            ->setSearch(['mid'=>'用户ID', 'member.name' => '姓名', 'member.mobile' => '手机号']) // 设置搜索框
            ->addColumns([ // 批量添加数据列
                ['id', 'ID'],
                ['order_no', '订单号'],
                ['mobile', '手机号'],
                ['name', '姓名'],
                ['money', '金额'],
                ['status', '状态'],
                ['type', '充值方式',['transfer'=>"线下转账","alipay"=>"支付宝"]],
                ['create_time', '充值时间', 'datetime'],
                ['right_button', '操作', 'btn']
            ])
            ->hideCheckbox()
            ->addTopButton('custem',$btn_excel)
            ->addRightButton('edit',[],['area' => ['800px', '90%'], 'title' => '充值审核']) // 批量添加右侧按钮
            ->replaceRightButton(['status' => '成功'], '<button class="btn btn-danger btn-xs" type="button" disabled>不可操作</button>')
            ->addOrder('id,create_time,status,money,order_no')
            ->setRowList($data_list)
            ->fetch(); // 渲染模板
   }



    public function getAgentWithdro(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $map=array('member.agent_far'=>session('user_auth')['uid']);
        $data_list = WithdrawModel::getAll($map, $order);
		
        // 分页数据
        $page = $data_list->render();
        if(empty($_SERVER["QUERY_STRING"])){
            $excel_url=http().$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]."_export";
        }else{
            $excel_url=http().$_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"]."_export?".$_SERVER["QUERY_STRING"];
        }
        $btn_excel = [
            'title' => '导出EXCEL表',
            'icon'  => 'fa fa-fw fa-download',
            'href'  => url($excel_url,'','')
        ];
        return ZBuilder::make('table')
            //->setSearch(['mid'=>'用户ID', 'member.name' => '姓名', 'member.mobile' => '手机号']) // 设置搜索框
            ->addColumns([ // 批量添加数据列
                ['id', 'ID'],
                ['order_no', '订单号'],
                ['mobile', '手机号'],
                ['name', '姓名'],
                ['money', '金额'],
                ['status', '状态',["处理中","提现成功","提现失败","提现退回"]],
                ['create_time', '提现时间', 'datetime'],
            ])
            ->hideCheckbox()
            //->addTopButton('custem',$btn_excel)
            ->addRightButton('edit',[],['area' => ['800px', '90%'], 'title' => '充值审核']) // 批量添加右侧按钮
            ->replaceRightButton(['status' => '成功'], '<button class="btn btn-danger btn-xs" type="button" disabled>不可操作</button>')
            ->addOrder('id,create_time,status,money,order_no')
            ->setRowList($data_list)
            ->fetch(); // 渲染模板
    }


    public function getAgentuserchicang(){
       
        $list_rows1 = input('list_rows');
        $listRows = isset($list_rows1)?$list_rows1:20;
        // 获取排序
   
        $position= new Position();
        // 读取数据
        $data=$position->get_position();
        foreach ($data as $v){
            Db::name('stock_position')->where(['id'=>$v['id']])->update($v);
        }
		$map = $this->getMap();
        //$data_list = Db::name('stock_position')->where($map)->where(['buying'=>0])->order($order)->paginate($listRows = 20);
        $data_list = Db::view('stock_position p')
            ->view('stock_subaccount s','sub_account','s.id=p.sub_id','left')
            ->view('member m','mobile','m.id=s.uid','left')
            ->where($map)
            ->where('m.agent_far',session('user_auth')['uid'])
            ->where(['p.buying'=>0])
            ->order($order)
            ->paginate($listRows);

        if(empty($_SERVER["QUERY_STRING"])){
            $excel_url=substr(http().$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"],0,-5)."_export";
        }else{
            $excel_url=substr(http().$_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"],0,-5)."_export?".$_SERVER["QUERY_STRING"];
        }
        $btn_excel = [
            'title' => '导出EXCEL表',
            'icon'  => 'fa fa-fw fa-download',
            'href'  => url($excel_url,'','')
        ];

        // 分页数据
        $page = $data_list->render();
        //自定义按钮（风控设置）
        $btn_risk = [
            'title' => '风控设置',
            'icon'  => 'fa fa-fw fa-balance-scale',
            'href'  => url('/stock/subaccount/risk', ['id' => '__sub_id__'])
        ];
        $btn_close = [
            'title' => '强制卖出',
            'icon'  => 'fa fa-fw fa-trash-o',
            'class' => 'btn btn-xs btn-default ajax-get confirm',
            'data-title' => '真的要卖出平仓吗？',
            'data-tips' => '请确认此股票已到了平仓线！',
            'href'  => url('close', ['id' => '__sub_id__','code'=>'__gupiao_code__','count'=>'__canbuy_count__'])
        ];
        return ZBuilder::make('table')
            ->setPageTitle('股票持仓') // 设置页面标题
            ->addTopButton('custem',$btn_excel)
            ->setTableName('stock_position') // 设置数据表名
            ->addOrder('sub_id,gupiao_name') // 添加排序
            ->addFilter('gupiao_code') // 添加筛选
            ->setSearch([ 'sub_account' => '子账户','mobile'=>'手机号'],'','',true) // 设置搜索参数
            ->addRightButton('risk', $btn_risk) // 添加子账户风控设置按钮
            ->addRightButton('close', $btn_close) // 强制卖出
            ->addColumns([ // 批量添加列
                ['sub_id', '子账户ID'],
                ['mobile', '手机号'],
                ['sub_account', '子账户'],
                ['lid', '交易账户名'],
//                ['soruce', '证券来源'],
//                ['login_name', '证券账户'],
                ['gupiao_code', '证券代码'],
                ['gupiao_name', '证券名称'],
                //['count', '证券数量'],
                //['stock_count', '实际持仓数量'],
                //['canbuy_count', '可卖数量'],
                ['stock_count', '持仓数量'],
                ['buy_average_price', '买入均价'],
                ['now_price', '当前价'],
                ['market_value', '最新市值'],
                ['ck_profit', '参考浮动盈亏'],
                ['profit_rate', '盈亏比例'],
                ['jiyisuo', '交易所'],
                ['right_button', '操作', 'btn'],
            ])

            ->hideCheckbox()
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch();
  }
    /*
     * 交割单
     */
    public function delivery(){

        $list_rows1 = input('list_rows');
        $listRows = isset($list_rows1)?$list_rows1:20;
        if(empty($map['deal_date'][1][0])){
            $beginday=date('Ymd',time()-2592000);//30天前
        }else{
            $beginday=date('Ymd',strtotime($map['deal_date'][1][0]));
        }
        if(empty($map['deal_date'][1][1])){
            $endday=date('Ymd',time());
        }else{
            $endday=date('Ymd',strtotime($map['deal_date'][1][1]));
        }
		
		// 获取查询条件
		$map=[];
		$keyword = trim(input('param.keyword/s', ''));
		if($keyword<>""){
			$map['sub_account|mobile'] = $keyword;
		}
		
        $data_list = Db::view('stock_delivery_order d')
            ->view('stock_subaccount s','sub_account','s.id=d.sub_id','left')
            ->view('member m','mobile','m.id=s.uid','left')
            ->where(['d.status'=>1])
            ->where($map)
            ->where('agent_far',session('user_auth')['uid'])
            ->order($order)
            ->paginate($listRows);
        if(empty($_SERVER["QUERY_STRING"])){
            $excel_url=substr(http().$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"],0,-5)."_export";
        }else{
            $excel_url=substr(http().$_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"],0,-5)."_export?".$_SERVER["QUERY_STRING"];
        }
        $btn_excel = [
            'title' => '导出EXCEL表',
            'icon'  => 'fa fa-fw fa-download',
            'href'  => url($excel_url,'','')
        ];
        // 分页数据
        $page = $data_list->render();
        return ZBuilder::make('table')
            ->setPageTitle('交割单') // 设置页面标题
            ->addTopButton('custem',$btn_excel)
            ->setTableName('stock_delivery_order') // 设置数据表名
            ->addTimeFilter('deal_date', [$beginday, $endday]) // 添加时间段筛选
            ->addOrder('sub_id,gupiao_name') // 添加排序
            ->addFilter('gupiao_code') // 添加筛选
            ->setSearch([ 'sub_account' => '子账户', 'mobile' => '商户手机号'],'','',true) // 设置搜索参数
            ->addRightButton('edit') // 添加编辑按钮
            ->addColumns([ // 批量添加列
                ['sub_id', '子账户ID'],
                ['mobile', '手机号'],
                ['sub_account', '子账户'],
                ['lid', '交易账户名'],
//                ['soruce', '证券来源'],
//                ['login_name', '证券账户'],
                ['gupiao_code', '证券代码'],
                ['gupiao_name', '证券名称'],
                ['deal_date', '成交日期','date'],
                ['business_name', '业务名称'],
                ['deal_price', '成交价格'],
                ['volume', '成交数量'],
                ['amount', '剩余数量'],
                ['residual_quantity', '成交金额'],
                ['liquidation_amount', '清算金额'],
                ['residual_amount', '剩余金额'],
                ['stamp_duty', '印花税'],
                ['transfer_fee', '过户费'],
                ['commission', '净佣金'],
                ['trust_no', '委托编号'],
                ['deal_no', '成交编号'],
            ])

            ->hideCheckbox()
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch();
    }
        /*
     * 当日委托
     */
    public function trust(){
		
        $list_rows1 = input('list_rows');
        $listRows = isset($list_rows1)?$list_rows1:20;
 
        // 获取查询条件
		$map=[];
		$keyword = trim(input('param.keyword/s', ''));
		if($keyword<>""){
			$map['sub_account|mobile'] = $keyword;
		}
		
        $time=strtotime(date('y-m-d',time()));
        $data_list = Db::view('stock_trust t')
            ->view('stock_subaccount s','sub_account','s.id=t.sub_id','left')
            ->view('member m','mobile','m.id=s.uid','left')
            ->where(['trust_date'=>$time])
            ->where($map)
            ->where('agent_far',session('user_auth')['uid'])
            ->order($order)
            ->paginate($listRows);
        if(empty($_SERVER["QUERY_STRING"])){
            $excel_url=substr(http().$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"],0,-5)."_export";
        }else{
            $excel_url=substr(http().$_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"],0,-5)."_export?".$_SERVER["QUERY_STRING"];
        }
        $btn_excel = [
            'title' => '导出EXCEL表',
            'icon'  => 'fa fa-fw fa-download',
            'href'  => url($excel_url,'','')
        ];
        // 分页数据
        $page = $data_list->render();
        return ZBuilder::make('table')
            ->setPageTitle('当日委托') // 设置页面标题
            ->addTopButton('custem',$btn_excel)
            ->setTableName('stock_trust') // 设置数据表名
            ->addOrder('sub_id,gupiao_name') // 添加排序
            ->addFilter('gupiao_code') // 添加筛选
            ->setSearch([ 'sub_account' => '子账户', 'mobile' => '商户手机号'],'','',true) // 设置搜索参数
            ->addRightButton('edit') // 添加编辑按钮
            ->addColumns([ // 批量添加列
                ['sub_id', '子账户ID'],
                ['mobile', '手机号'],
                ['sub_account', '子账户'],
                ['lid', '交易账户名'],
                //['soruce', '证券来源'],
                //['login_name', '证券账户'],
                ['gupiao_code', '证券代码'],
                ['gupiao_name', '证券名称'],
                ['trust_date', '委托日期','date'],
                ['trust_time', '委托时间'],
                ['trust_no', '委托编号'],
                ['trust_price', '委托价格'],
                ['trust_count', '委托数量'],
                ['flag2', '买卖标志'],
                ['volume', '成交数量'],
                ['amount', '成交金额'],
                ['cancel_order_count', '撤单数量'],
                ['status', '状态说明'],
            ])

            ->hideCheckbox()
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch();
    }
  
  
	public function    usermoney(){
        	cookie('__forward__', $_SERVER['REQUEST_URI']);
        // 获取查询条件
  
        $map=array('member.agent_far'=>session('user_auth')['uid']);
        // 数据列表
        $data_list = MoneyModel::getAll($map, $order);

       // 分页数据 
        $page = $data_list->render();

        if(empty($_SERVER["QUERY_STRING"])){
            $excel_url=substr(http().$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"],0,-
                5)."_export";
        }else{
            $excel_url=substr(http().$_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"],0,-
                5)."_export?".$_SERVER["QUERY_STRING"];
        }
        $btn_excel = [
            'title' => '导出EXCEL表',
            'icon'  => 'fa fa-fw fa-download',
            'href'  => url($excel_url,'','')
        ];

    	return ZBuilder::make('table')
            ->setSearch(['mid'=>'用户ID','member.name' => '姓名', 'member.mobile' => '手机号']) // 设置搜索框
            ->addColumns([ // 批量添加数据列
                ['id', 'ID'],
                ['mobile', '手机号'],
                ['name', '姓名'],
                ['account', '可用资金'],
                ['freeze', '冻结金额'],
                ['operate_account', '操盘总额'],
                ['bond_account', '保证金总额'],
                //['status', '状态', 'switch'],
            ])
            ->hideCheckbox()
            ->setTableName('money')
            ->addTopButton('custem',$btn_excel)
            //->addTopButtons('enable,disable') // 批量添加顶部按钮
            ->addRightButtons(['edit']) // 批量添加右侧按钮
            ->addOrder('id,account,freeze,status,operate_account,bond_account')
     		->setRowList($data_list)
            ->fetch(); // 渲染模板
    }

	/**
     * 获取筛选条件
     * @author 路人甲乙 
     * @alter 小乌 <82950492@qq.com>
     * @return array
     */
    protected function getMap()
    {
        $search_field     = input('param.search_field/s', '');
        $_search_field    = input('param._search_field/s', '');
        $keyword          = input('param.keyword/s', '');
        $filter           = input('param._filter/s', '');
        $filter_content   = input('param._filter_content/s', '');
        $filter_time      = input('param._filter_time/s', '');
        $filter_time2     = input('param._filter_time2/s', '');
        $filter_time_from = input('param._filter_time_from/s', '');
        $filter_time_to   = input('param._filter_time_to/s', '');
        $select_field     = input('param._select_field/s', '');
        $select_value     = input('param._select_value/s', '');
        $search_area      = input('param._s', '');
        $search_area_op   = input('param._o', '');

        $map = [];

        // 搜索框搜索
        if ($search_field != '' && $keyword !== '') {
            $map[$search_field] = ['like', "%$keyword%"];
        }
        //精确搜索
        if ($_search_field != '' && $keyword !== '') {
            $map[$_search_field] = ['like', "$keyword"];
        }

        // 下拉筛选
        if ($select_field != '') {
            $select_field = array_filter(explode('|', $select_field), 'strlen');
            $select_value = array_filter(explode('|', $select_value), 'strlen');
            foreach ($select_field as $key => $item) {
                if ($select_value[$key] != '_all') {
                    $map[$item] = $select_value[$key];
                }
            }
        }

        // 时间段搜索
        if ($filter_time != '' && $filter_time_from != '' && $filter_time_to != '') {
            $map[$filter_time] = ['between time', [$filter_time_from.' 00:00:00', $filter_time_to.' 23:59:59']];
        }
        // 时间段搜索-时间戳
        if ($filter_time2 != '' && $filter_time_from != '' && $filter_time_to != '') {
            $map[$filter_time2] = ['between time', [$filter_time_from, $filter_time_to]];
        }


        // 表头筛选
        if ($filter != '') {
            $filter         = array_filter(explode('|', $filter), 'strlen');
            $filter_content = array_filter(explode('|', $filter_content), 'strlen');
            foreach ($filter as $key => $item) {
                if (isset($filter_content[$key])) {
                    $map[$item] = ['in', $filter_content[$key]];
                }
            }
        }

        // 搜索区域
        if ($search_area != '') {
            $search_area = explode('|', $search_area);
            $search_area_op = explode('|', $search_area_op);
            foreach ($search_area as $key => $item) {
                list($field, $value) = explode('=', $item);
                $op = explode('=', $search_area_op[$key]);
                if ($value != '') {
                    switch ($op[1]) {
                        case 'like':
                            $map[$field] = ['like', "%$value%"];
                            break;
                        case 'between time':
                        case 'not between time':
                            $value = explode(' - ', $value);
                        default:
                            $map[$field] = [$op[1], $value];
                    }
                }
            }
        }
        return $map;
    }
	
	/**
     * 设置分页参数
     * @author 路人甲乙 
     */
    final protected function setPageParam()
    {
        $list_rows = input('?param.list_rows') ? input('param.list_rows') : config('list_rows');
        config('paginate.list_rows', $list_rows);
        config('paginate.query', input('get.'));
    }

}
  
